/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: Shentong
 * @Date: 2021-04-09 12:34:34
 * @LastEditors: Shentong
 * @LastEditTime: 2021-12-29 18:45:06
 */
 import React, { useEffect, useState } from "react";
 import { View, Image } from "@tarojs/components";

 import Taro, { useDidShow, useDidHide, useRouter } from "@tarojs/taro";

 import { connect } from 'react-redux'

 import { userAPIAuthSeting, getStoregeByKey } from '@/utils/index'

 import { getSchoolList }  from '@/api/school'

 import curLocationIcon from '@/src/assets/icon/curLocationIcon.png'
 import reLocation from '@/src/assets/icon/reLocation.png'

 import { AtList, AtListItem, AtSearchBar } from "taro-ui"

 import styles from './index.module.scss'

 interface ISchool {
  schoolId: Number | string;
  schoolName: string
 }

 const SchoolList = (props) => {
   const { setCurSchool, dispatch } = props

   const [schools, setSchools] = useState<Array<ISchool>>([]);

   const [schoolKey, setSchoolKey] = useState<string>('')
   // 经纬度
   const [locationInfo, setLocationInfo] = useState({})
   // 获取当前本地存储的个人信息
   const [userInfo, setUserInfo] = useState({})

   const routerParams = useRouter().params;

  //  获取学校
  const getSchools = async ({key = schoolKey, lat = locationInfo.lat || '', lon = locationInfo.lon || ''} = {}) => {
    Taro.showLoading({ title: "加载中...", mask: true });
    // 本地存储的'userInfo'
    const _userInfo = await getStoregeByKey('userInfo') || {}

    const params = {
      schoolName: key,
      lat,
      lon
    }

    getSchoolList(params).then((res) => {
      const { data } = res
      setSchools(data)

      const defaultSchool = data && data.length ? data[0] : {}

      const storageUserInfo = Object.keys(_userInfo).length ? _userInfo : defaultSchool

      Taro.setStorageSync('userInfo', Object.assign(storageUserInfo, { lat, lon }))

      setUserInfo(storageUserInfo)

      Taro.hideLoading();
    })
  }

  const getLocation = () => {
    userAPIAuthSeting('scope.userLocation',{},() => {
      Taro.getLocation({
        type: 'gcj02', //返回可以用于 Taro.openLocation的经纬度
        success: function (res) {
          const { latitude: lat, longitude:lon } = res
          setLocationInfo({ lat, lon })

          getSchools({ lat, lon })
        }
      })
    })
  }

  // 选择学校
  const schoolSelected = async (school) => {
    // 从选择地址跳过来的
    if (routerParams.isFromAddress === '1') {
      dispatch({ type: 'UPDATE_CUR_SCHOOL', payload: { ...school, ...locationInfo }})

      Taro.navigateBack()
    } else {
      Taro.setStorageSync('userInfo', Object.assign(userInfo,school, locationInfo))

      Taro.reLaunch({url: '/pages/index/index'})
    }

  }

  const shcoolKeyOnchange = (key) => setSchoolKey(key)

  const reLocationClick = async () => {
    await Taro.vibrateShort()

    if(locationInfo.lat && locationInfo.lon) getSchools()
    else getLocation()
  }

  const clearSchoolKey = () => {
    setSchoolKey('')
    getSchools({key: ''})
  }

  useDidShow(async ()=> {
    getLocation()
  })

  // useEffect(() => {
  //   Taro.startLocationUpdate({
  //     success: res => {
  //       console.log('res', res)
  //     }
  //   })
  //   return Taro.stopLocationUpdate({
  //     success: res => {
  //       console.log('关闭监听成功', res)
  //     }
  //   })
  // },[])

   return (
     <View className={styles.schoolList}>
       <View className={styles.searchHeader}>
        <AtSearchBar
          placeholder='请输入学校关键字'
          actionName='搜索'
          value={schoolKey}
          onChange={shcoolKeyOnchange}
          onActionClick={() => getSchools()}
          onClear={clearSchoolKey}
          onConfirm={() => getSchools()}
        />
        <View className={styles.doLocation}>
          <View className={styles.currentLocation}>
            <View>当前位置</View>
            <Image src={curLocationIcon} className={styles.locaitonIcon} />
            <View className={styles.lightHight}>{userInfo.schoolName || '未选择'}</View>
          </View>
          <View className={styles.currentLocation} onClick={reLocationClick}>
            <Image src={reLocation} className={styles.locaitonIcon} />
            <View>重新定位</View>
          </View>
        </View>
       </View>
       <AtList className={styles.list}>
       {
         schools.map((item, indexx) => {
          return (
            <AtListItem title={item.schoolName} onClick={() => schoolSelected(item)} key={`school_${indexx}`} />
          )
        })
         }

        </AtList>
     </View>
   );
 }

 export default connect(({ setCurSchool }) => ({  setCurSchool }), dispatch => ({
  dispatch
}))(SchoolList)
